package com.taiji.web.controller.workOrder;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.taiji.common.core.domain.R;
import com.taiji.common.core.domain.entity.SysUser;
import com.taiji.common.utils.SecurityUtils;
import com.taiji.common.utils.uuid.IdUtils;
import com.taiji.system.service.ISysUserService;
import com.taiji.workOrder.domain.Message;
import com.taiji.workOrder.domain.MessageBody;
import com.taiji.workOrder.domain.WorkOrder;
import com.taiji.workOrder.mapper.MessageMapper;
import com.taiji.workOrder.service.IMyDealService;
import io.swagger.annotations.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.taiji.common.annotation.Log;
import com.taiji.common.core.controller.BaseController;
import com.taiji.common.core.domain.AjaxResult;
import com.taiji.common.enums.BusinessType;
import com.taiji.workOrder.service.IMyOrderService;
import com.taiji.common.utils.poi.ExcelUtil;
import com.taiji.common.core.page.TableDataInfo;

/**
 * 我的工单Controller
 *
 * @author taiji
 * @date 2023-03-04
 */
@Api(tags="工单管理")
@RestController
@RequestMapping("/workOrder/myOrder")
public class MyOrderController extends BaseController
{
    @Autowired
    private IMyOrderService myOrderService;

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private IMyDealService myDealService;
    @Autowired
    private ISysUserService userService;
    /**
     * 查询我的工单列表
     */
    @PreAuthorize("@ss.hasPermi('workOrder:myOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(WorkOrder workOrder)
    {
        startPage();
        List<WorkOrder> list = myOrderService.selectMyOrderList(workOrder);
        return getDataTable(list);
    }

    /**
     * 导出我的工单列表
     */
    @PreAuthorize("@ss.hasPermi('workOrder:myOrder:export')")
    @Log(title = "我的工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WorkOrder workOrder)
    {
        List<WorkOrder> list = myOrderService.selectMyOrderList(workOrder);
        ExcelUtil<WorkOrder> util = new ExcelUtil<WorkOrder>(WorkOrder.class);
        util.exportExcel(response, list, "我的工单数据");
    }

    /**
     * 获取我的工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('workOrder:myOrder:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取我的工单详细信息")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(myOrderService.selectMyOrderById(id));
    }

    /**
     * 新增我的工单
     */
    @PreAuthorize("@ss.hasPermi('workOrder:myOrder:add')")
    @Log(title = "我的工单", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增我的工单")
    public AjaxResult add(@Valid @RequestBody WorkOrder workOrder) throws Exception {
        return toAjax(myOrderService.insertMyOrder(workOrder));
    }

    /**
     * 修改我的工单
     */
    @PreAuthorize("@ss.hasPermi('workOrder:myOrder:edit')")
    @Log(title = "我的工单", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改我的工单")
    public AjaxResult edit(@Valid @RequestBody WorkOrder workOrder)
    {
        return toAjax(myOrderService.updateMyOrder(workOrder));
    }

    /**
     * 删除我的工单
     */
    @PreAuthorize("@ss.hasPermi('workOrder:myOrder:remove')")
    @Log(title = "我的工单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除我的工单")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(myOrderService.deleteMyOrderByIds(ids));
    }


    /**
     * 获取我的工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('workOrder:myOrder:query')")
    @GetMapping(value = "/getDetail/{id}")
    @ApiOperation("获取我的工单详细信息")
    public AjaxResult getDetail(@PathVariable("id") String id)
    {
        return success(myOrderService.getDetail(id));
    }

    /**
     *  转单时的接单人 下拉选（本项目中的人员）
     */
    @ApiOperation("转单时的接单人 下拉选")
    @GetMapping(value = "/getDealPerson/{projectCode}")
    public R getDealPerson(@PathVariable("projectCode") String projectCode)
    {
        return R.ok(myOrderService.getDealPerson(projectCode));

    }

    /**
     * 转单
     */

    @ApiOperation("转单")
    @Log(title = "转单", businessType = BusinessType.INSERT)
    @PostMapping("/revert")
    public AjaxResult revert(@RequestBody WorkOrder workOrder) throws Exception {
        String remark = workOrder.getRemark();
        int revert = myOrderService.revert(workOrder);
        if (revert > 0) {
            String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
            WorkOrder workOrder1 = myOrderService.selectMyOrderById(workOrder.getId());
            MessageBody messageBody = new MessageBody();
            messageBody.setId(IdUtils.randomUUID());
            messageBody.setSendTime(new Date());
            messageBody.setFromName(nickName);
            messageBody.setType("转单");
            messageBody.setToName(workOrder.getDealPerson());
            messageBody.setContent(workOrder1.getName()+"工单转单信息,工单编号："+workOrder1.getWorkNumber());
            boolean flag =false;
            try {
                flag= WebSocketServer.sendMessageToUser(messageBody);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SysUser sysUser = userService.selectUserByUserName(workOrder.getDealPerson());

            Message message = Message.getMessage(messageBody);
            if (remark==null){
                remark="无";
            }
            message.setContent(workOrder1.getWorkNumber()+"工单进行转单操作"+"\n"+"转单发起人："+nickName
            +"\n"+"工单接收人："+sysUser.getNickName()+"\n"+"转单备注："+remark);
            message.setTitle(workOrder1.getWorkNumber()+"转单提醒");
            message.setProjectCode(workOrder1.getProjectCode());
            message.setServerName("");
            message.setInfoType("转单");
//            if (flag) {
//                message.setStatus(1);
//            }
            messageMapper.insertMessage(message);
            return AjaxResult.success();
        }

        return AjaxResult.error();
    }

    /**
     * 完成工单
     */

    @ApiOperation("完成工单")
    @Log(title = "完成工单", businessType = BusinessType.INSERT)
    @PostMapping("/finish")
    public AjaxResult finish(@RequestBody WorkOrder workOrder) throws Exception {
        int finish = myOrderService.finish(workOrder.getWorkNumber());

        if (finish > 0) {
            //向工单创建人发送消息推送
            String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
            WorkOrder workOrder1 =  myDealService.selectWorkOrderByWorkNumber(workOrder.getWorkNumber());
            MessageBody messageBody = new MessageBody();
            messageBody.setId(IdUtils.fastSimpleUUID());
            messageBody.setSendTime(new Date());
            messageBody.setFromName(nickName);
            messageBody.setType("完成");
            messageBody.setToName(workOrder1.getCreateBy());
            messageBody.setContent(workOrder1.getName()+"工单完成,工单编号: "+workOrder1.getWorkNumber());
            boolean flag =false;
            try {
                flag= WebSocketServer.sendMessageToUser(messageBody);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Message message = Message.getMessage(messageBody);
            message.setTitle(workOrder1.getWorkNumber()+"完成提醒");
            message.setContent(workOrder1.getWorkNumber()+"工单进行完成操作"+"\n"+"完成发起人："+nickName);
            message.setProjectCode(workOrder1.getProjectCode());
            message.setServerName("");
            message.setInfoType("完成");
//            if (flag) {
//                //已读
//                message.setStatus(1);
//            }
            messageMapper.insertMessage(message);
            return AjaxResult.success();
        }


        return AjaxResult.error();
    }
    /**
     * 关闭工单
     */

    @ApiOperation("关闭工单")
    @Log(title = "关闭工单", businessType = BusinessType.INSERT)
    @PostMapping("/close")
    public AjaxResult close(@RequestBody WorkOrder workOrder) throws Exception {
        String remark = workOrder.getRemark();
        String dealPerson;
        int close = myOrderService.close(workOrder.getWorkNumber(), remark);
        if (close > 0){
            String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
            WorkOrder workOrder1 =  myDealService.selectWorkOrderByWorkNumber(workOrder.getWorkNumber());
            dealPerson = workOrder1.getDealPerson();
            MessageBody messageBody = new MessageBody();
            messageBody.setId(IdUtils.fastSimpleUUID());
            messageBody.setSendTime(new Date());
            messageBody.setFromName(nickName);
            messageBody.setType("关闭");
            messageBody.setToName(dealPerson);
            messageBody.setContent(workOrder1.getName()+"工单关闭,工单编号: "+workOrder1.getWorkNumber());
            boolean flag =false;
            if (dealPerson != null && !dealPerson.isEmpty()) {
                try {
                    flag= WebSocketServer.sendMessageToUser(messageBody);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Message message = Message.getMessage(messageBody);
            if (remark==null){
                remark="无";
            }
            message.setContent(workOrder1.getWorkNumber()+"工单进行关闭操作"+"\n"+"关闭发起人："+nickName
                    +"\n"+"关闭备注："+remark);
            message.setTitle(workOrder1.getWorkNumber()+"关闭提醒");
            message.setProjectCode(workOrder1.getProjectCode());
            message.setServerName("");
            message.setInfoType("关闭");
//            if (flag) {
//                //已读
//                message.setStatus(1);
//            }
            if (dealPerson != null && !dealPerson.isEmpty()) {
                messageMapper.insertMessage(message);
            }

            return AjaxResult.success();
        }
//        return AjaxResult.error();
        return AjaxResult.success();
    }

    /**
     * 驳回工单
     */

    @ApiOperation("驳回工单")
    @Log(title = "驳回工单", businessType = BusinessType.INSERT)
    @PostMapping("/disallowed")
    public AjaxResult disallowed(@RequestBody WorkOrder workOrder) throws Exception {
        String remark = workOrder.getRemark();
        String dealPerson;
        int disallowed = myOrderService.disallowed(workOrder.getWorkNumber(), remark);
        if (disallowed > 0){
            String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
            WorkOrder workOrder1 =  myDealService.selectWorkOrderByWorkNumber(workOrder.getWorkNumber());
            dealPerson = workOrder1.getDealPerson();
            MessageBody messageBody = new MessageBody();
            messageBody.setId(IdUtils.fastSimpleUUID());
            messageBody.setSendTime(new Date());
            messageBody.setFromName(nickName);
            messageBody.setType("驳回");
            messageBody.setToName(dealPerson);
            messageBody.setContent(workOrder1.getName()+"工单驳回,工单编号: "+workOrder1.getWorkNumber());
            boolean flag =false;
            if (dealPerson != null && !dealPerson.isEmpty()) {
                try {
                    flag= WebSocketServer.sendMessageToUser(messageBody);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Message message = Message.getMessage(messageBody);
            if (remark==null){
                remark="无";
            }
            message.setContent(workOrder1.getWorkNumber()+"工单进行驳回操作"+"\n"+"驳回发起人："+nickName
                    +"\n"+"驳回备注："+remark);
            message.setTitle(workOrder1.getWorkNumber()+"驳回提醒");
            message.setProjectCode(workOrder1.getProjectCode());
            message.setServerName("");
            message.setInfoType("驳回");
//            if (flag) {
//                //已读
//                message.setStatus(1);
//            }
            if (dealPerson != null && !dealPerson.isEmpty()) {
                messageMapper.insertMessage(message);
            }

            return AjaxResult.success();
        }
//        return AjaxResult.error();
        return AjaxResult.success();
    }

    /**
     * 受理工单
     */

    @ApiOperation("受理工单")
    @Log(title = "受理工单", businessType = BusinessType.INSERT)
    @PostMapping("/accept")
    public AjaxResult accept(@RequestBody WorkOrder workOrder) throws Exception {
        return toAjax(myOrderService.accept(workOrder.getWorkNumber()));
    }

    /**
     * 提交工单
     */
    @ApiOperation("提交工单")
    @Log(title = "提交工单", businessType = BusinessType.INSERT)
    @PostMapping("/submitOrder")
    public AjaxResult submit(@RequestBody WorkOrder workOrder) throws Exception {
        return toAjax(myOrderService.submit(workOrder.getWorkNumber()));
    }

}
